package com.kuang.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @program: juc
 * @description: forkjoin完成求和计算的操作
 * @author: 陈恩涛
 * @create: 2021-03-23 15:35
 **/
public class ForkJoinDemo extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    //临界值
    private Long cv = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    public static void main(String[] args) {

    }

    @Override
    protected Long compute() {
        if (end - start > cv) {
            //forkjoin
            //如何使用ForkJoin
            // 1、forkjoinPool通过它来执行
            // 2、计算任务forkjoinPool.execute(ForkJoinTask<?> task)
            // 3、计算类继承ForkJoinTask
            long mid = (start + end) / 2;
            ForkJoinDemo task1 = new ForkJoinDemo(start, mid);
            task1.fork(); //拆分任务，把任务压入线程队列
            ForkJoinDemo task2 = new ForkJoinDemo(mid+1, end);
            task2.fork();
            return task1.join() + task2.join();

        } else {
            //直接计算
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }
    }
}
